<template>
  <div class="role-management">
    <div class="page-header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="showAddDialog">添加角色</el-button>
    </div>

    <!-- 角色列表 -->
    <el-card>
      <el-table :data="roleList" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色代码" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="userCount" label="用户数量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'active'" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="editRole(row)">编辑</el-button>
            <el-button type="info" link @click="setPermissions(row)">权限</el-button>
            <el-button 
              v-if="row.code !== 'super'" 
              type="danger" 
              link 
              @click="deleteRole(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogMode === 'add' ? '添加角色' : '编辑角色'" 
      width="500px"
    >
      <el-form :model="roleForm" :rules="formRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色代码" prop="code">
          <el-input 
            v-model="roleForm.code" 
            placeholder="请输入角色代码" 
            :disabled="dialogMode === 'edit'"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="roleForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="权限设置" width="800px">
      <div class="permission-header">
        <h3>{{ currentRole?.name }} - 权限配置</h3>
      </div>
      
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :check-strictly="false"
        class="permission-tree"
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <span class="node-label">{{ data.name }}</span>
            <span class="node-desc" v-if="data.description">{{ data.description }}</span>
          </div>
        </template>
      </el-tree>
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissions">保存权限</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'RoleManagement',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const permissionDialogVisible = ref(false)
    const dialogMode = ref('add')
    const roleFormRef = ref(null)
    const permissionTreeRef = ref(null)
    const currentRole = ref(null)
    
    // 角色表单
    const roleForm = reactive({
      name: '',
      code: '',
      status: 'active',
      description: ''
    })
    
    // 表单验证规则
    const formRules = {
      name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
      code: [
        { required: true, message: '请输入角色代码', trigger: 'blur' },
        { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '角色代码只能包含字母、数字和下划线，且以字母或下划线开头', trigger: 'blur' }
      ],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }
    
    // 角色列表
    const roleList = ref([
      {
        id: 1,
        name: '超级管理员',
        code: 'super',
        description: '系统超级管理员，拥有所有权限',
        userCount: 1,
        status: 'active',
        createdAt: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        name: '管理员',
        code: 'admin',
        description: '普通管理员，拥有大部分管理权限',
        userCount: 5,
        status: 'active',
        createdAt: '2024-01-02 14:30:00'
      },
      {
        id: 3,
        name: '操作员',
        code: 'operator',
        description: '操作员，拥有基本操作权限',
        userCount: 8,
        status: 'active',
        createdAt: '2024-01-03 09:15:00'
      }
    ])
    
    // 权限树配置
    const treeProps = {
      children: 'children',
      label: 'name'
    }
    
    // 权限树数据
    const permissionTree = ref([
      {
        id: 1,
        name: '仪表盘',
        description: '首页仪表盘查看',
        children: [
          { id: 11, name: '查看仪表盘', description: '查看系统概览数据' }
        ]
      },
      {
        id: 2,
        name: '场馆管理',
        description: '场馆相关功能',
        children: [
          { id: 21, name: '场馆列表', description: '查看场馆列表' },
          { id: 22, name: '添加场馆', description: '添加新场馆' },
          { id: 23, name: '编辑场馆', description: '编辑场馆信息' },
          { id: 24, name: '删除场馆', description: '删除场馆' }
        ]
      },
      {
        id: 3,
        name: '活动管理',
        description: '活动相关功能',
        children: [
          { id: 31, name: '活动列表', description: '查看活动列表' },
          { id: 32, name: '活动详情', description: '查看活动详情' },
          { id: 33, name: '审核活动', description: '审核活动申请' }
        ]
      },
      {
        id: 4,
        name: '用户管理',
        description: '用户相关功能',
        children: [
          { id: 41, name: '用户列表', description: '查看用户列表' },
          { id: 42, name: '用户详情', description: '查看用户详情' },
          { id: 43, name: '禁用用户', description: '禁用/启用用户' }
        ]
      },
      {
        id: 5,
        name: '订单管理',
        description: '订单相关功能',
        children: [
          { id: 51, name: '订单列表', description: '查看订单列表' },
          { id: 52, name: '订单统计', description: '查看订单统计' },
          { id: 53, name: '退款处理', description: '处理退款申请' }
        ]
      },
      {
        id: 6,
        name: '支付管理',
        description: '支付相关功能',
        children: [
          { id: 61, name: '支付记录', description: '查看支付记录' },
          { id: 62, name: '支付设置', description: '配置支付参数' }
        ]
      },
      {
        id: 7,
        name: '设备管理',
        description: '设备相关功能',
        children: [
          { id: 71, name: '设备列表', description: '查看设备列表' },
          { id: 72, name: '设备控制', description: '控制设备操作' }
        ]
      },
      {
        id: 8,
        name: '系统管理',
        description: '系统相关功能',
        children: [
          { id: 81, name: '管理员管理', description: '管理系统管理员' },
          { id: 82, name: '角色管理', description: '管理用户角色' },
          { id: 83, name: '系统设置', description: '系统参数配置' },
          { id: 84, name: '系统日志', description: '查看系统日志' }
        ]
      }
    ])
    
    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        // 这里调用API加载角色列表
        console.log('加载角色列表数据')
      } catch (error) {
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 显示添加对话框
    const showAddDialog = () => {
      dialogMode.value = 'add'
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑角色
    const editRole = (role) => {
      dialogMode.value = 'edit'
      Object.assign(roleForm, role)
      dialogVisible.value = true
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(roleForm, {
        name: '',
        code: '',
        status: 'active',
        description: ''
      })
      roleFormRef.value?.clearValidate()
    }
    
    // 提交表单
    const submitForm = async () => {
      try {
        await roleFormRef.value.validate()
        
        if (dialogMode.value === 'add') {
          // 这里调用添加API
          ElMessage.success('角色添加成功')
        } else {
          // 这里调用编辑API
          ElMessage.success('角色更新成功')
        }
        
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.log('表单验证失败')
      }
    }
    
    // 删除角色
    const deleteRole = async (role) => {
      try {
        await ElMessageBox.confirm('确认要删除这个角色吗？删除后相关用户的角色将被清空。', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 这里调用删除API
        ElMessage.success('角色删除成功')
        loadData()
      } catch (error) {
        console.log('取消删除')
      }
    }
    
    // 设置权限
    const setPermissions = async (role) => {
      currentRole.value = role
      
      // 加载当前角色的权限
      try {
        // 这里调用API获取角色权限
        const checkedKeys = [11, 21, 22, 31, 41, 51] // 示例权限ID
        
        // 设置选中的权限
        setTimeout(() => {
          permissionTreeRef.value?.setCheckedKeys(checkedKeys)
        }, 100)
        
        permissionDialogVisible.value = true
      } catch (error) {
        ElMessage.error('获取权限数据失败')
      }
    }
    
    // 保存权限
    const savePermissions = async () => {
      try {
        const checkedKeys = permissionTreeRef.value?.getCheckedKeys()
        const halfCheckedKeys = permissionTreeRef.value?.getHalfCheckedKeys()
        
        // 这里调用API保存权限
        console.log('保存权限:', { checkedKeys, halfCheckedKeys })
        
        ElMessage.success('权限保存成功')
        permissionDialogVisible.value = false
      } catch (error) {
        ElMessage.error('保存权限失败')
      }
    }
    
    onMounted(() => {
      loadData()
    })
    
    return {
      loading,
      roleList,
      dialogVisible,
      permissionDialogVisible,
      dialogMode,
      roleForm,
      formRules,
      roleFormRef,
      permissionTreeRef,
      currentRole,
      permissionTree,
      treeProps,
      showAddDialog,
      editRole,
      submitForm,
      deleteRole,
      setPermissions,
      savePermissions
    }
  }
}
</script>

<style lang="scss" scoped>
.role-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h2 {
    color: var(--text-color-primary);
    font-weight: 500;
  }
}

.permission-header {
  margin-bottom: 20px;
  
  h3 {
    color: var(--text-color-primary);
    font-weight: 500;
    margin: 0;
  }
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  padding: 10px;
  
  .tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .node-label {
      font-weight: 500;
    }
    
    .node-desc {
      font-size: 12px;
      color: var(--text-color-secondary);
    }
  }
}
</style> 